package com.kgc.app.controller;

import com.github.pagehelper.PageInfo;
import com.kgc.app.condition.AppInfoCondition;
import com.kgc.app.dto.AppInfoDto;
import com.kgc.app.pojo.AppInfo;
import com.kgc.app.pojo.DataDictionary;
import com.kgc.app.pojo.DevUser;
import com.kgc.app.service.AppInfoService;
import com.kgc.app.service.DataDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/appinfo")
public class AppInfoController {

    @Autowired
    private AppInfoService appInfoService;

    @Autowired
    private DataDictionaryService dictionaryService;


    /**
     * 查询所有信息
     * @param appInfoCondition  页面传递过来的查询条件
     * @param session   用获取页面登录的用户信息
     * @param model     用于存储提示信息
     * @return
     */
    @RequestMapping("/list")
    public String list(AppInfoCondition appInfoCondition, HttpSession session, Model model){

        //判断用户是不是第一次登录
        //获取域中的用户对象
        DevUser devUser = (DevUser)session.getAttribute("devUser");

        //判断用户是否登录
        if (null == devUser){
            model.addAttribute("error","请登录后再查询");

            return "forward:/jsp/devlogin.jsp";
        }

        //登录后，把用户ID存入到参数对象中
        appInfoCondition.setDevId(devUser.getId());

        PageInfo<AppInfoDto> appInfoDtos = appInfoService.selectAppInfoByCondition(appInfoCondition);

        model.addAttribute("appInfoDtos",appInfoDtos);

        model.addAttribute("appInfoCondition",appInfoCondition);

        return "/developer/appinfolist";
    }

    /**
     * 添加app信息
     * @param appInfo   页面传递过来的app信息
     * @param session   用获取页面登录的用户信息
     * @return
     */
    @RequestMapping("add")
    @ResponseBody
    public Map<String,Object> add(AppInfo appInfo,HttpSession session){
        System.out.println(appInfo);
        Map<String, Object> map = new HashMap<String, Object>();
        DevUser devUser = (DevUser)session.getAttribute("devUser");
        if (null == devUser){
            map.put("code",404);
            map.put("msg","请登录后在添加数据！");
            return map;
        }

        appInfo.setDevId(devUser.getId());
        appInfo.setCreatedBy(devUser.getId());
        appInfo.setCreationDate(new Date());

        //调
        boolean b = appInfoService.addAppInfo(appInfo);

        if (b){
            map.put("code",200);
            map.put("sucess","添加成功！");
        }else {
            map.put("code",500);
            map.put("sucess","添加失败！");
        }

        return map;
    }

    /**
     * apk名称唯一性校验
     * @param APKName   页面的apk名称
     * @return
     */
    @RequestMapping("findAppinfoByAPKName")
    @ResponseBody
    public Map<String,Object> findAppinfoByAPKName(String APKName){

        boolean appinfoByAPKName = appInfoService.findAppinfoByAPKName(APKName);

        Map<String, Object> map = new HashMap<String, Object>();

        if (appinfoByAPKName){
            map.put("code",200);
            map.put("msg","此APKName可用");
        }else {
            map.put("code",404);
            map.put("msg","此APKName不可用");
        }

        return map;
    }


    /**
     * 异步文件上传
     * @param a_logoPicPath 文件上传项的名称
     * @param session
     * @return
     */
    @RequestMapping("ajaxFileUpload")
    @ResponseBody
    public Map<String,Object> ajaxFileUpload(MultipartFile a_logoPicPath,HttpSession session){
        //创建一个map集合用于存储返回给页面的信息
        Map<String, Object> map = new HashMap<String, Object>();

        //验证文件类型
        //获取上传的文件名
        String originalFilename = a_logoPicPath.getOriginalFilename();
        //然后得到这个文件的后缀
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //判断文件后缀是否符合要求，如果不符合则返回错误信息
        if (!suffixName.equalsIgnoreCase(".jpg") &&
            !suffixName.equalsIgnoreCase(".jpeg") &&
            !suffixName.equalsIgnoreCase(".png")){
            map.put("code",500);
            map.put("msg","文件格式错误");
            return map;
        }

        //验证文件的大小 不能超过3MB
        //获取文件大小
        long size = a_logoPicPath.getSize();
        //判断文件大小
        if (size > 1024*1024*3){
            map.put("code",500);
            map.put("msg","文件过大，请重新选择！");
            return map;
        }

        //开始进行文件上传操作
        /**
         * 创建一个新的文件名称
         *      randomUUID      生成一个通用唯一识别码（中间包含"-"）
         *      replace         去掉通用唯一识别码中间的"-"
         */
        String newFileName = UUID.randomUUID().toString().replace("-", "") + suffixName;

        //指定上传路径
        ServletContext application = session.getServletContext();
        String realPath = application.getRealPath("/fileUpload/img");

        //生成上传文件夹
        File realPathFile = new File(realPath);
        //判断此文件夹是否存在
        if (!realPathFile.exists()){
            //不存在则创建一个
            realPathFile.mkdirs();
        }

        //生成上传文件对象
        File file = new File(realPathFile, newFileName);
        try {
            a_logoPicPath.transferTo(file);//上传完成
            map.put("code",200);
            map.put("msg","文件上传成功！");
            map.put("filePath","/fileUpload/img/"+newFileName);
        } catch (IOException e) {
            map.put("code",500);
            map.put("msg","文件上传失败！");
            e.printStackTrace();
        }

        return map;
    }

    @RequestMapping("/view")
    public String selectByAppId(Long id, Long valueId,HttpSession session,Model model){

        DevUser devUser = (DevUser)session.getAttribute("devUser");

        if (null == devUser){
            model.addAttribute("error","请先登录再进行修改！");
            return "forward:/jsp/devlogin.jsp";
        }


        AppInfo appInfo = appInfoService.viewAppInfo(id);

        DataDictionary dictionary = dictionaryService.selectByTypeNameAndValueId("APP状态", valueId);

        appInfo.setDictionary(dictionary);

        model.addAttribute("appInfo",appInfo);


        return "/developer/appinfomodify";
    }

    @RequestMapping("/update")
    public String updateAppInfo(AppInfo appInfo,HttpSession session,Model model){
        DevUser devUser = (DevUser)session.getAttribute("devUser");

        if (null == devUser){
            model.addAttribute("error","请先登录再进行修改！");
            return "forward:/jsp/devlogin.jsp";
        }

        appInfo.setModifyDate(new Date());
        appInfo.setModifyBy(devUser.getId());

        Integer row = appInfoService.updateAppInfo(appInfo);

        if (row > 0){
            return "redirect:/appinfo/list";
        }else {
            model.addAttribute("error","修改失败！请重新修改！");
            return "forward:/jsp/developer/appinfomodify.jsp";
        }

    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable Long id){

        appInfoService.deleteAppInfoById(id);

        return "forward:/appinfo/list";
    }
}
